package com.kx.yooli.kx.wechat.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.kx.yooli.kx.wechat.config.propertiesconf.CustomizedPropertyConfigurer;
import com.kx.yooli.kx.wechat.config.wx.WechatInit;
import com.kx.yooli.kx.wechat.constant.Constants;
import com.kx.yooli.kx.wechat.constant.ErrorCodeMsg;
import com.kx.yooli.kx.wechat.entity.nplm.CustInfo;
import com.kx.yooli.kx.wechat.mapper.nplm.CustInfoMapper;
import com.kx.yooli.kx.wechat.mapper.paycard.WechatPaycardMapper;
import com.kx.yooli.kx.wechat.mapper.user.UserInfoMapper;
import com.kx.yooli.kx.wechat.mapper.user.UserInfoSsoMapper;
import com.kx.yooli.kx.wechat.po.paycard.WechatPaycard;
import com.kx.yooli.kx.wechat.po.result.AjaxResult;
import com.kx.yooli.kx.wechat.po.user.UserInfo;
import com.kx.yooli.kx.wechat.po.user.UserInfoSso;
import com.kx.yooli.kx.wechat.service.sys.IUserService;
import com.kx.yooli.kx.wechat.utils.http.HttpUtils;
import com.kx.yooli.kx.wechat.utils.redis.RedisUtil;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author john_sqwen-childe.wen
 * @date 2024/3/29
 * @PROJECT_NAME wechat
 * @description create UserServiceImpl by john_sqwen
 * and userService value is
 */
@Component
public class UserServiceImpl implements IUserService {
    private final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private CustInfoMapper custInfoMapper;

    @Resource
    private WechatInit walletInit;

    @Resource
    private UserInfoSsoMapper userInfoSsoMapper;
    @Override
    public AjaxResult userGoLogin(String o) {
        log.info("JSONObject parse value is  {}",JSONObject.parse(o));
        String phone = JSONObject.parseObject(o).getString("phone");
        String code = JSONObject.parseObject( o).getString("verifyCode");
        String imgCode = JSONObject.parseObject( o).getString("imgCode");
        String type = JSONObject.parseObject( o).getString("type");
        String sid = JSONObject.parseObject( o).getString("sid");

        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)||StringUtils.isEmpty(type)||StringUtils.isEmpty(imgCode)||StringUtils.isEmpty(sid)){
            return AjaxResult.error("必填项为空");
        }
        if (!Constants.DEFAULT_LOGIN.equals(type)){
            walletInit.obtainOpenId();
        }
        Map<String,Object> map = null;
        try {
            String vaildCode = (String) redisUtil.get(phone);
            if (StringUtils.isEmpty(vaildCode)) {
                log.info("the error value is {}",AjaxResult.error("短信验证码未发送"));
                return AjaxResult.error("短信验证码未发送");
            }
            if (!redisUtil.get(phone).equals(code)) {
                return AjaxResult.error("短信验证码错误");
            }
            if (!redisUtil.exists("verifyCode::" + sid)) {
                return AjaxResult.error("请重新获取图形验证码");
            }
            if (!String.valueOf(redisUtil.get("verifyCode::" + sid)).equals(imgCode)) {
                return AjaxResult.error("图形验证码错误");
            }
            map =  getUserInfo(o);
            if (!map.get("code").equals(ErrorCodeMsg.SUCCESS_NET_EXCEPTION.getCode())){
                return AjaxResult.success(Integer.parseInt(map.get("code").toString()),map.get("msg").toString(),map.get("data"));
            }
        }catch (Exception e){
            log.info("this method has error please check you function{}",e.getMessage());
            return AjaxResult.error("网络请求失败！");
        }
        return AjaxResult.success(map.get("data"));
    }

    @Override
    public AjaxResult goRegister(String o) {
        String phone = JSONObject.parseObject(o).getString("phone");
        String idCard = JSONObject.parseObject( o).getString("idCard");
        String username = JSONObject.parseObject( o).getString("username");
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(idCard)||StringUtils.isEmpty(username)){
            return AjaxResult.error("必填项为空");
        }
        UserInfo userInfo = userInfoMapper.selectByCertNo(idCard);
        CustInfo custInfo = custInfoMapper.selectByCertNo(idCard);
        UserInfoSso infoSso = userInfoSsoMapper.selectByCertNoDefault(idCard);
        if (infoSso!=null){
            if (!infoSso.getMobile().equals(phone)){
                infoSso.setMobile(phone);
                userInfoSsoMapper.updateMobileByCertNo(infoSso);
                return AjaxResult.success("修改成功",infoSso);
            }
            return AjaxResult.error("该用户已注册,可直接登录！",infoSso);
        }
        if (userInfo == null ){
            if (custInfo == null){
                userInfo = new UserInfo();
                userInfo.setMobile(phone);
                userInfo.setCertNo(idCard);
                userInfo.setName(username);
                userInfo.setMobile(phone);
                return AjaxResult.error("该用户尚未查询到贷款!",userInfo);
            }
            if (!custInfo.getCustName().equals(username)){
                return AjaxResult.error("用户姓名不匹配");
            }
            UserInfoSso userInfoSso = new UserInfoSso();
            userInfoSso.setCertNo(custInfo.getCertNo());
            userInfoSso.setCustNo(custInfo.getCustNo());
            userInfoSso.setName(custInfo.getCustName());
            userInfoSso.setMobile(phone);
            userInfoSsoMapper.insert(userInfoSso);
            return AjaxResult.success(userInfoSso);
        }
        //username匹配校验
        if (!userInfo.getName().equals(username)){
            return AjaxResult.error("用户姓名不匹配");
        }
        userInfo.setName(username);
        userInfo.setMobile(phone);
        userInfoMapper.updateMobileByCertNo(userInfo);
        Map<String,Object> map =  getUserInfo(o);
        if (!map.get("code").equals(ErrorCodeMsg.SUCCESS_NET_EXCEPTION.getCode())){
            return AjaxResult.success(Integer.parseInt(map.get("code").toString()),map.get("msg").toString(),map.get("data"));
        }
        UserInfo info  = map.get("data") instanceof UserInfo ? (UserInfo) map.get("data") : null;
        return AjaxResult.success(info);
    }

    @Override
    public AjaxResult initInfo(String o) {
        String code = JSONObject.parseObject( o).getString("code");
        String url = CustomizedPropertyConfigurer.getContextProperty("wechat.access.url");
        String appid =CustomizedPropertyConfigurer.getContextProperty("app.id");
        String secret = CustomizedPropertyConfigurer.getContextProperty("app.secret");
        if (StringUtils.isEmpty(code)){
            return AjaxResult.error("code为空");
        }
        try {
            // 构造请求参数
            String params = "?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
            String response = HttpUtils.sendGet(url,params);
            log.info("response return is {}",response);
            String access_token = JSONObject.parseObject(response).getString("access_token");
            String openid = JSONObject.parseObject(response).getString("openid");
            if (StringUtils.isEmpty(access_token)||StringUtils.isEmpty(openid)){
                return AjaxResult.error("微信授权失败，请重新刷新！");
            }
            redisUtil.set("access_token::"+access_token,access_token,7200L);
            // 这里简单返回微信返回的原始JSON字符串，实际应用中应该解析并处理响应
            return AjaxResult.success("微信授权成功",access_token);
        }catch (Exception e){
            log.error("this method has error please check you function{}",e.getMessage());
            return AjaxResult.error("网络请求失败！");
        }

    }

    @Override
    public AjaxResult getUserInfo(String o) {
        String phone = JSONObject.parseObject(o).getString("phone");
        if (StringUtils.isEmpty(phone)){
            return AjaxResult.error("手机号为空");
        }
        UserInfo info = userInfoMapper.selectByPhoneDefault(phone);
        UserInfoSso custInfo = userInfoSsoMapper.selectByPhoneDefault(phone);
        if (info == null){
            if (custInfo == null){
                return AjaxResult.error(ErrorCodeMsg.USER_NOT_EXIST_EXCEPTION.getCode(),ErrorCodeMsg.USER_NOT_EXIST_EXCEPTION.getDesc());
            }
            if( null == custInfo.getCertNo() ||  custInfo.getCertNo().isBlank())
            {
                return AjaxResult.error(ErrorCodeMsg.USER_NOT_EXIST_EXCEPTION.getCode(),ErrorCodeMsg.USER_NOT_EXIST_EXCEPTION.getDesc());
            }
            info = new UserInfo();
            info.setCertNo(custInfo.getCertNo());
            info.setName(custInfo.getName());
            info.setId(custInfo.getId());
            info.setMobile(phone);
            return AjaxResult.success(info);
        }
        return AjaxResult.success("获取信息成功",info);
    }
    @Transactional
    @Override
    public AjaxResult updateUserInfo(UserInfo o) {
        if (StringUtils.isEmpty(o.getMobile())||StringUtils.isEmpty(o.getCertNo())||StringUtils.isEmpty(o.getName())){
            return AjaxResult.error("必填项为空");
        }
        List<UserInfoSso> infoSsoIphone = userInfoSsoMapper.selectPhoneOrCertNo(o.getMobile(),o.getCertNo());
        UserInfoSso userInfoSso =  null;
        if (infoSsoIphone.size() ==0){
            return AjaxResult.error("用户不存在");
        }
        for (UserInfoSso infoSso : infoSsoIphone){
            if (infoSso.getMobile().equals(o.getMobile())){
                return AjaxResult.error("该手机号已被使用");
            }
            if (!infoSso.getCertNo().equals(o.getCertNo())){
                continue;
            }
            userInfoSso = infoSso;
        }
        try {
            if (userInfoSso == null){
                return AjaxResult.error("用户不存在");
            }
            if (userInfoSso.getName().equals("sso")){
                userInfoSso.setMobile(o.getMobile());
                userInfoSsoMapper.updateMobileByCertNo(userInfoSso);
            }else {
                userInfoMapper.updateMobileByCertNo(o);
            }
            return AjaxResult.success("更新成功",o);
        }catch (Exception e){
            log.error("this method has error please check you function{}",e.getMessage());
            return AjaxResult.error("更新失败");
        }

    }
}
